package thread;

// volatile 测试两个线程调用同一个方法
// 只保证了内存可见性，没有保证原子性！
// 所以此时是线程不安全的

public class Demo11 {
    static class Counter {
        volatile public int count = 0;  // 保证了可见性

        public void increase() {
            count++;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5_0000; i++) {
                counter.increase();
            }
        });

        Thread t2 = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 5_0000; i++) {
                    counter.increase();
                }
            }
        };

        t1.start();
        t2.start();

        t1.join();
        t2.join(); // 等待阻塞

        System.out.println("counter: " + counter.count);
    }
}
